// 用户设置控制面板显示和隐藏
document.getElementById("openSetPanelBtn").addEventListener("click", function (event) {
    event.preventDefault(); // 阻止默认行为
    document.getElementById("setRightPanel").classList.toggle("show");
    document.getElementById("backdrop").style.display = "block"; // 显示遮罩层
});

// 用户评论控制面板显示和隐藏
document.getElementById("openCommentPanelBtn").addEventListener("click", function (event) {
    event.preventDefault(); // 阻止默认行为
    document.getElementById("commentRightPanel").classList.toggle("show");
    document.getElementById("backdrop").style.display = "block"; // 显示遮罩层
});


// 点击遮罩层时隐藏面板
document.getElementById("backdrop").addEventListener("click", function () {
    document.getElementById("setRightPanel").classList.remove("show");
    document.getElementById("commentRightPanel").classList.remove("show");
    document.getElementById("backdrop").style.display = "none"; // 隐藏遮罩层
});


/*<----------------------------------------评论页面start---------------------------------->*/
// 需要改，数据库实现
// 点赞按钮
const likeButton = document.querySelector('.like-button');
let likeCount = 0; // 初始点赞数

likeButton.addEventListener('click', () => {
    likeCount++;
    likeButton.innerHTML = `<i class="ph ph-heart"></i> 赞 (${likeCount})`;
});

// 发布评论按钮
const submitCommentButton = document.getElementById('submitCommentButton');
const userCommentInput = document.getElementById('userCommentInput');
const commentsList = document.querySelector('.comments-list');

// 监听评论发布按钮
submitCommentButton.addEventListener('click', () => {
    const commentText = userCommentInput.value.trim();

    if (commentText !== '') {
        // 将评论输入到数据库，待实现

        // 清空输入框并关闭模态框
        userCommentInput.value = '';
        const modal = bootstrap.Modal.getInstance(document.getElementById('commentModal'));
        modal.hide();
    }
});

/*<----------------------------------------评论页面end---------------------------------->*/


// <---------------------------处理文件上传start--------------------------->
// 处理文件上传
function handleFileUpload(event, type) {
    const file = event.target.files[0]; // 获取文件
    if (file) {
        // 检查文件类型
        if (file.type !== "application/octet-stream" && !file.name.endsWith('.mat')) {
            alert("请上传 .mat 文件！");
            return;
        }

        // 创建FormData对象来传送文件
        const formData = new FormData();
        formData.append(type + "File", file); // 将文件加入到formData中

        // 上传文件到后端
        fetch('/upload', { // 假设后端接口是 /upload
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                console.log("上传成功", data);
                // 在这里可以处理上传成功后的操作
            })
            .catch(error => {
                console.error("上传失败", error);
                alert("上传失败，请重试！");
            });
    }
}


// <---------------------------处理文件上传end--------------------------->


// <------------------------------处理响应式图例显示start------------------------------------------->
// Function to fetch prediction data from the backend

async function fetchPredictionData() {
    const response = await fetch('/get_prediction');
    const data = await response.json();
    return data;
}

// Function to draw the image using the prediction data
function drawImage(outputs, targetNames, eachAcc, categoryColors) {
    const canvas = document.getElementById("ProgressImageCanvas");
    const ctx = canvas.getContext("2d");

    const canvasWidth = 350;
    const canvasHeight = 350;
    const numRows = outputs.length;
    const numCols = outputs[0].length;

    const pixelWidth = canvasWidth / numCols;
    const pixelHeight = canvasHeight / numRows;


    // Draw the outputs on the canvas
    for (let y = 0; y < numRows; y++) {
        for (let x = 0; x < numCols; x++) {
            const category = outputs[y][x] - 1; // Adjust for 0-based index
            if (category >= 0) {
                ctx.fillStyle = categoryColors[category];
            } else {
                ctx.fillStyle = '#000000'; // If category is 0, make it black
            }
            ctx.fillRect(x * pixelWidth, y * pixelHeight, pixelWidth, pixelHeight); // Draw pixel block
        }
    }

    // Add hover event to display category info
    const card = document.getElementById("showTypeCard");

    canvas.addEventListener("mousemove", function (event) {
        const rect = canvas.getBoundingClientRect();
        // console.log(rect);
        // console.log(event.clientX);
        // console.log(event.clientY);

        const x = Math.floor((event.clientX - rect.left) / pixelWidth);
        const y = Math.floor((event.clientY - rect.top) / pixelHeight);
        // console.log(x);
        // console.log(y);
        const category = outputs[y][x] - 1; // Get category index

        if (category >= 0) {
            const categoryName = targetNames[category];
            const accuracy = eachAcc[category].toFixed(2);

            card.innerHTML = `类&nbsp;&nbsp;&nbsp;别： ${categoryName}<br>准确率： ${accuracy}%`;
            card.style.left = `${event.clientX + 10}px`;
            card.style.top = `${event.clientY + 10}px`;
            card.style.display = "block";
        } else {
            card.style.display = "none"; // Hide card if category is 0
        }
    });

    canvas.addEventListener("mouseout", function () {
        card.style.display = "none";
    });
}

 // 测试用
 const targetNames = ['Alfalfa', 'Corn-notill', 'Corn-mintill', 'Corn', 'Grass-pasture', 'Grass-trees',
     'Grass-pasture-mowed', 'Hay-windrowed', 'Oats', 'Soybean-notill', 'Soybean-mintill', 'Soybean-clean',
     'Wheat', 'Woods', 'Buildings-Grass-Trees-Drives', 'Stone-Steel-Towers'
 ];

 const eachAcc = [91.30434783, 97.68907563, 98.91566265, 100., 99.79296066, 97.53424658, 100., 100., 100., 98.25102881, 97.80040733, 97.80775717, 98.53658537, 99.84189723, 96.89119171, 94.62365591];

 // Example of output data (replace this with actual data from Python backend)
 const outputs = [
     [0, 3, 3, 3, 3, 1, 1, 2, 2, 5, 5, 6, 6, 6, 6, 6],
     [3, 3, 3, 3, 3, 1, 1, 2, 2, 5, 5, 6, 6, 6, 6, 16],
     [3, 3, 3, 3, 3, 1, 1, 2, 2, 5, 5, 6, 6, 6, 6, 6],
     [3, 3, 3, 3, 3, 1, 1, 2, 2, 5, 5, 6, 6, 16, 6, 6],
     [3, 3, 3, 3, 3, 1, 1, 2, 2, 5, 5, 6, 6, 6, 6, 6],
     [3, 3, 3, 3, 3, 1, 1, 2, 2, 5, 5, 6, 6, 6, 6, 6],
     [3, 3, 3, 3, 3, 1, 1, 2, 2, 5, 5, 6, 6, 6, 6, 6],
     [3, 3, 3, 3, 3, 1, 1, 2, 2, 5, 5, 6, 6, 6, 6, 6],
     [3, 3, 3, 3, 3, 1, 1, 2, 2, 5, 5, 6, 6, 6, 6, 6],
     [3, 3, 3, 3, 3, 1, 1, 2, 2, 5, 5, 6, 6, 6, 6, 6],
     [3, 3, 3, 3, 3, 1, 1, 2, 2, 5, 5, 6, 6, 6, 6, 6],
     [3, 3, 3, 3, 3, 1, 1, 2, 2, 5, 5, 6, 6, 6, 6, 6],
     [3, 3, 3, 3, 3, 1, 1, 2, 2, 5, 5, 6, 6, 6, 6, 6],
     [3, 3, 3, 3, 3, 1, 1, 2, 2, 5, 5, 6, 6, 6, 6, 6],
     [3, 3, 3, 3, 3, 1, 1, 2, 2, 5, 5, 6, 6, 6, 6, 6],
     [3, 3, 3, 3, 3, 1, 1, 2, 2, 5, 5, 6, 0, 0, 0, 0]
 ];

 // Function to generate colors for each category (you can customize this)
 const categoryColors = [
    '#89442c', '#0200fa', '#fc6500', '#02fd80', '#a24b9d', '#65b0fa',
    '#77fea7', '#395b6d', '#fffc05', '#feff7a', '#fc02fe', '#6401fb',
    '#00aff4', '#05fc05', '#aab153', '#60c03a'
];

 drawImage(outputs, targetNames, eachAcc, categoryColors);
// Load the prediction data and render the image
fetchPredictionData().then(data => {
    const outputs = data.outputs;
    const targetNames = data.target_names;
    const eachAcc = data.each_acc;
    const categoryColors = data.category_colors;
    drawImage(outputs, targetNames, eachAcc, categoryColors);
});

// <------------------------------处理响应式图例显示end------------------------------------------->